<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10 paddingBottom20">
        <div class="main_crumbs boxdq">
          <div class="main_crumbs_l">
            <a href="javascript:;" @click="$router.back(-1)">
              <i class="el-icon-arrow-down"></i>返回
            </a>
            <em>|</em>
            <span>差额流水</span>
          </div>
        </div>
        <div class="mainor_form batch-wrap form-item-mg mg-t-14">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="80px"
          >
            <el-form-item label="用户：" prop="uid">
              <change-user-input
                ref="changeUserInput"
                @sendValue="getUser"
                @clear="clearUid"
                :name_value="user_change_name"
              ></change-user-input>
            </el-form-item>
            <el-form-item label="订单号：" prop="order_sn">
              <el-input
                v-model.trim="form.order_sn"
                placeholder="订单号"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <el-form-item label="创建日期：" prop="createTime">
              <el-date-picker
                v-model="createTime"
                type="daterange"
                class="time220"
                :editable="false"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :clearable="false"
                :picker-options="pickerOptions"
              />
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="false">
              <el-button @click="exportOrderiInfo">导出</el-button>
            </MainFormBtn>
          </el-form>
        </div>
        <div class="main_table" style="min-height: 550px">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list.list.data"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
            @selection-change="handleSelectionChange"
          >
            <!-- <el-table-column type="selection" /> -->
            <el-table-column label="用户名称" prop="">
              <template slot-scope="scope">{{
                scope.row.member ? scope.row.member.nickname : ""
              }}</template>
            </el-table-column>
            <el-table-column label="关联订单" prop="">
              <template slot-scope="scope">{{
                scope.row.order ? scope.row.order.order_sn : ""
              }}</template>
            </el-table-column>
            <el-table-column label="流水类型" prop="status">
              <template slot-scope="scope">{{
                list.typeList[scope.row.type]
              }}</template>
            </el-table-column>
            <el-table-column label="金额" prop="balance_change" />
            <el-table-column label="变动后差额" prop="balance_left" />
            <el-table-column label="流水状态" prop="">
              <template slot-scope="scope">
                <span :class="'status' + scope.row.status">
                  {{ statusList[scope.row.status] }}</span
                >
              </template>
            </el-table-column>

            <el-table-column
              label="创建日期"
              width="180"
              prop="related_order_sn"
            >
              <template slot-scope="scope">{{
                parseTime(scope.row.created_at)
              }}</template>
            </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 导出弹出框 -->
    <el-dialog
      title="导出差额流水"
      :visible.sync="exportbuVisible"
      class="main_dialog dialog500"
    >
      <div v-if="selectArr.length == 0 ? true : false">
        <p class="exptitle">选择导出时间</p>
        <el-date-picker
          v-model="exportTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          @change="datepicker"
        >
        </el-date-picker>
        <!-- <el-tooltip
          class="item"
          effect="dark"
          content="时间范围只能选择一个月之内"
          placement="bottom"
        >
          <i class="el-icon-question"></i>
        </el-tooltip> -->
      </div>
      <div v-if="selectArr.length == 0 ? true : false">
        <p class="exptitle company_name">用户名称</p>
        <change-user-input
          ref="changeUserInputDia"
          @sendValue="getUserDia"
          @clear="clearUidiaDia"
        ></change-user-input>
      </div>
      <div v-if="selectArr.length == 0 ? false : true" class="maintip">
        你已经选择了<span>{{ selectArr.length }}</span
        >行数据
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exportbuVisible = false">取 消</el-button>
        <el-button type="primary" @click="exportConfirm" v-repeatClick
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  balanceWater_index,
  export_user_balanceWater_list,
} from "@/api/financial/financialSalesman";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import dateOption from "@/options/dateOption";
import { parseTime, exportMethod } from "@/utils/index";

export default {
  components: {},
  data() {
    return {
      // 时间
      parseTime,
      exportMethod,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      list: {
        list: [],
      },
      createTime: [],
      pickerOptions: dateOption,
      listLoading: false,
      // 搜索
      form: {
        order_sn: "",
        uid: "",
        start_time: "",
        end_time: "",
      },
      user_change_name: "",
      typeList: [],
      statusList: ["已关闭", "确认中", "正常"],
      exportbuVisible: false,
      // 全选
      selectArr: [],
      // 导出时间
      exportTime: "",
      selectname: "",
      export_uid: "",
    };
  },
  created() {
    if (this.$route.params.date) {
      this.form.uid = this.$route.params.date.id;
      let name = "";
      if (this.$route.params.date.nickname) {
        name = this.$route.params.date.nickname;
        this.user_change_name = name;
      }
    }

    // 列表
    this.balanceWater_index();
  },
  methods: {
    //获取用户信息
    getUserDia(data) {
      let uid = data.info.user_id;
      this.export_uid = uid;
    },
    // 清除用户的uid
    clearUidiaDia() {
      this.export_uid = "";
    },
    //获取用户信息
    getUser(data) {
      let uid = data.info.user_id;
      this.form.uid = uid;
      this.balanceWater_index();
    },
    // 清除用户的uid
    clearUid() {
      this.form.uid = "";
    },
    // 结差额
    knotClick(ind) {
      this.$confirm(
        "差额为负数时，需用户在线支付差额，完成差额清零！",
        "提示",
        {
          confirmButtonText: "确定",
          type: "warning",
        }
      )
        .then(() => {})
        .catch(() => {});
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.balanceWater_index();
    },
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.createTime = [];
      this.$refs["changeUserInput"].name = "";
      this.current.page = 1;
      this.balanceWater_index();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.balanceWater_index();
    },
    changePage(page) {
      this.current.page = page;
      this.balanceWater_index();
    },
    // 列表
    balanceWater_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      balanceWater_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.list = res.data;
          this.totalCount = res.data.list.total;
          this.typeList = res.data.typeList;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.start_time = this.createTime[0] ? this.createTime[0] : "";
      form.end_time = this.createTime[1] ? this.createTime[1] : "";
      return form;
    },
    // 监听全选
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push(item.id);
      });
    },
    exportConfirm() {
      let ids = "";
      let send_time = "";
      let end_time = "";
      if (this.exportTime.length == 0) {
        this.$message.error("请输入需要导出的日期");
        return;
      }
      if (this.exportTime.length > 0) {
        send_time = this.exportTime[0];
        end_time = this.exportTime[1];
      }
      let form = {
        start_time: send_time,
        end_time: end_time,
        uid: this.export_uid,
      };

      if (!this.export_uid) {
        delete form.uid;
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, form)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        form
      );
      this.exportbuVisible = false;
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_user_balanceWater_list(data)
        .then((res) => {
          this.exportMethod(res, "用户差额流水", notify);
        })
        .catch(() => {
          this.$message.error("导出失败");
        });
    },
    // 导出时间范围
    datepicker(val) {
      let start = "";
      let end = "";
      if (val) {
        start = new Date(val[0]).getTime();
        end = new Date(val[1]).getTime();
        let cha = end - start;
        if (cha > 30 * 24 * 60 * 60 * 1000) {
          this.$message.error("选择范围不能超过一个月，请重新选择");
          this.exportTime = "";
        }
      }
    },

    // 导出
    exportOrderiInfo() {
      this.exportbuVisible = true;
      this.exportTime = [];
      this.export_uid = "";
      if (this.$refs.changeUserInputDia) {
        this.$refs.changeUserInputDia.name = "";
      }
      let form = {};
      if (this.selectArr.length > 0) {
        form.ids = this.selectArr.join(",");
      } else {
        let idarr = [];
        this.list.list.data.forEach((item) => {
          idarr.push(item.id);
        });
        form.ids = idarr.join(",");
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        form
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_user_balanceWater_list(data)
        .then((res) => {
          this.exportMethod(res, "用户差额流水", notify);
        })
        .catch((err) => {
          this.$message.error("导出失败");
        });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: calc(100% - 220px);
  }
}
// 导出订单表头
.exptitle {
  display: block;
  font-size: 16px;
  color: #000000;
  margin: 0 0 10px;
}
.company_name {
  padding-top: 15px;
}
.maintip {
  text-align: center;
  padding-top: 15px;
  font-size: 18px;
  span {
    display: inline;
    padding: 18px 0;
    color: red;
  }
}
.new_navbar_svg {
  vertical-align: top;
  margin-left: 5px;
  use {
    fill: #ffffff;
  }
}
.status0 {
  color: red;
}
.status1 {
  color: #118ab2;
}
.status2 {
  color: #03a98e;
}
</style>
